import React, { useRef, useEffect, useState } from 'react';
import { Input, Button, Message, Loading, Form } from '@knownsec/react-component';
import cookie from 'react-cookies';
import { useHistory } from 'react-router-dom';
import CheckMfa from '@/components/CheckMfa';
import cn from 'classnames';
import s from './style.module.css';
import { login, register, productInfoHeader, validateMfa,getSystemDisk } from '~/API';
import loginIcon from '/static/loginRight.png';
import { getErrorMessage } from '@/common/constant'

function Login() { 
  !localStorage.oem&&(localStorage.oem=JSON.stringify({"title":"创宇 WebSOC 网络资产安全检测系统","home":"北京知道创宇信息技术股份有限公司"}))
  !localStorage.product&&(localStorage.product=JSON.stringify({"status":"","is_trial":""}))
  const text=JSON.parse(localStorage.oem)
  const history = useHistory();
  const loginForm = useRef();
  const [loginBtn, setLoginBtn] = useState(false);
  const [showLoading, setLoading] = useState(false);
  const [mfaData, setMfaData] = useState({});
  const [mfaVisible, setMfaVisible] = useState(false);
  const [captchaImg, setCaptchaImg] = React.useState(`/api/v1/captcha/?v=${Math.random()}`);
  const [isFull, setIsFull] = useState('');

  useEffect(() => {
     vifiyUpcert()
  }, []);
  const submitLogin = () => {
    if(loginBtn){
        return false
    }
    const data = loginForm.current.getFieldsValue();
    if (!data.username) {
      return Message.show({
        type: 'error',
        message: '用户名不能为空',
      });
    }
    if (!data.password) {
      return Message.show({
        type: 'error',
        message: '密码不能为空',
      });
    }
    setLoginBtn(true)
    login(data)
      .then((res) => {
        if (res.status.toLowerCase() === 'success') {
            if (res.data?.is_mfa) {
                setMfaData(res.data.args);
                setMfaVisible(true);
            } else {
                cookie.save('refresh', res.data.refresh);
                cookie.save('token', res.data.token);
                cookie.save('username', res.data.username);
                // const action = getUserInfo(res.user_group[0])
                // store.dispatch(action)
                // sessionStorage.setItem('group', res.user_group[0]);
                localStorage.setItem('group', res.user_group[0]);
                if (res?.user_group[0] === '审计员') {
                    // window.location.href = '#/report_center';
                    window.location.href = '#/log_center';    
                } else {
                    history.push('/monitor');
                }
            }
        }
      })
      .catch((err) => {
        Message.show({
          type: 'error',
          message: typeof err.message === 'object' ? Object.values(err.message)[0] : err.message,
          onclose: () => {
            changeCaptcha();
          },
        });
        setTimeout(() => {
            setLoginBtn(false)
          },2000)
      });
  };
  const getMfa = val => {
    const obj = Object.assign({}, mfaData)
    obj.mfa_token = val
    validateMfa('POST', obj, false)
      .then(res => {
        if (res.status === 'success') {
          cookie.save('refresh', res.data.refresh)
          cookie.save('token', res.data.token)
          cookie.save('username', res.data.username)
          setMfaVisible(false)
          localStorage.setItem('group', res.user_group[0]);
          if (res?.user_group[0] === '审计员') {
              window.location.href = '#/report_center';
          } else {
              history.push('/');
          }
        }
      })
      .catch(err =>
        Message.show({ type: 'error', message: getErrorMessage(err.message) })
      )
  }
  const vifiyUpcert = () => {
    setLoading(true)
    productInfoHeader('GET').then(pi => {
        if(pi?.data?.product_status === '有效' || pi?.data?.product_status === 'is_expired'){
            localStorage.product=JSON.stringify({
              status: pi?.data?.product_status,
              is_trial:pi?.data?.is_trial
            })
            setLoading(false);
            ddisk()
        }else{
            history.push({pathname: '/upcert?'+pi?.data?.device_id});
        }
    }).catch(err => {
        history.push({pathname: '/upcert'});
    })
  }
  const changeCaptcha = () => {
    setCaptchaImg('/api/v1/captcha/?v=' + Math.random());
    loginForm.current.setFieldsValue({
      captcha: '',
    });
  };
  const ddisk = async () => {
    const res = await getSystemDisk({ master: 1 });
    let text=''
    if (res.data?.threshold<=res.data?.out_memery?.data_usage) {
        text='硬盘使用率达到系统危险上限，系统不能登录，请通知管理员！'
        setLoginBtn(true)
        }
    setIsFull(text);
  };
  return (
    <div className={s.wrapper}>
        
    <Loading show={showLoading} label="" />
      <div className={cn(s.login)}>
        <div className={s.form}>
          <div className={s.logo}></div>
          <Form
            ref={loginForm}
            onValuesChange={(newItem) => {
              const values = Object.keys(newItem).reduce((total, key) => {
                total[key] = newItem[key].value;
                return total;
              }, {});
              loginForm.current.setFieldsValue(values);
            }}
          >
            <Form.Item name="username">
              <Input className={s.input} placeholder="用户名" />
            </Form.Item>
            <Form.Item name="password">
              <Input className={s.input} type="password" placeholder="密码" />
            </Form.Item>
            <Form.Item name="captcha">
              <Input
                className={s.inputCaptcha}
                captchaImg={captchaImg}
                onChangeCaptcha={changeCaptcha}
                onKeyDown={(e) => {
                  if (e.keyCode == 13) {
                    submitLogin();
                  }
                }}
                captcha={true}
              />
            </Form.Item>
          </Form>
          <Button type="primary" onClick={submitLogin} disabled={loginBtn}>
            登录
          </Button>
          <p className={s.wordMain_h} style={{ display: isFull ? 'block' : 'none' }}>
              {isFull}
            </p>
        </div>
        <img src={loginIcon} className={s.loginIcon} />
      </div>
      <div className={s.title}>{text.home}</div>
      <CheckMfa visible={mfaVisible} getMfa={(v) => getMfa(v)} setVis={(v) => setMfaVisible(v)} />
    </div>
  );
}

export default Login;
